import { ComponentClass } from 'react'
import { connect } from '@tarojs/redux'

import Taro, { Component, Config } from '@tarojs/taro'
import { View, Text, Image, Input } from '@tarojs/components'

import { AtButton, AtList, AtListItem, AtCurtain } from 'taro-ui'

import XGood from '../../components/XGood'
import YTableDivider from '../../components/YTableDivider'
import ProfileAvatar from '../../containers/ProfileAvatar'

import join1 from '../../assets/join1@2x.png'
import join2 from '../../assets/join2.png'
import cloverIcon from '../../assets/cloverActive@2x.png'

import { image_prefix } from '../../utils'
import { queryProfile, queryUsers, createProfile } from '../../actions/goods'

import './index.scss'

type PageStateProps = {
  goods: object | {},
}

type PageDispatchProps = {
  fetchProfile: (object) => void,
  fetchUsers: (object) => void
}

type PageOwnProps = {
  goods: {
    profile: {
      data: {
        id: number
      }
    },
    users: {
      pagination: { count: number },
      // data: PageOwnGoodsUsersProps[]
    }
  },
  fetchProfile: (params: object, callback: (data: { errno: number }) => void) => {}
  fetchUsers: (params: object, callback: (data: { errno: number }) => void) => {}
}

type PageState = {}

type IProps = PageStateProps & PageDispatchProps & PageOwnProps

interface Profile {
  props: IProps
}

@connect(({ goods }) => ({
  goods
}), (dispatch) => ({
  fetchProfile(params, callback) {
    dispatch(queryProfile(params, callback))
  },
  fetchUsers(params, callback) {
    dispatch(queryUsers(params, callback))
  },
  addProfile(params, callback) {
    dispatch(createProfile(params, callback))
  },  
}))
class Profile extends Component {
  config: Config = {
    navigationBarTitleText: '详情'
  }

  state = {
    visible: false,
    isJoinOpened: false,
    isLanchGoodsOpened: false,
    goodsPrizeId: 0,
  }

  componentWillReceiveProps(nextProps) {
    console.log(this.props, nextProps)
  }

  componentWillUnmount() { }

  componentWillMount() {
    this.props.fetchProfile(this.$router.params, (data) => {
      if (data.errno || typeof data === 'string' ) {
        Taro.showToast({ title: `获取抽奖详情失败`, icon: 'none' })
      }
    })
    this.props.fetchUsers(this.$router.params)
  }

  componentDidMount() {
    const goodsPrizeId = this.props.goods.profile.data.GoodsPrizes[0].id
    this.setState(state => ({
      ...state,
      goodsPrizeId
    }))
  }

  componentDidShow() { }

  componentDidHide() { }

  //分享按钮函数
  onShareAppMessage() {
    return {
      title: '幸运草小程序',
      path: 'pages/home/index',
      success(res) {
        console.log("转发成功:" + JSON.stringify(res))
      },
      fail(res) {
        console.log("转发失败:" + JSON.stringify(res))
      }
    }
  }

  onGetPhoneNumber = msg => {
    console.log(msg)
  }

  handleLaunchGoods = msg => {
    // 阻止事件冒泡
    msg.stopPropagation()

    Taro.navigateBack({ delta: 2 })
    .then(results => {
      Taro.switchTab({url: '/pages/activity/index'})
      console.log(results)
    })
    // Taro.redirectTo({
    //   url: `/pages/home/index`
    // })
    // this.setState(state => ({
    //   ...state,
    //   visible: !state.visible
    // }))
  }

  onToShare = msg => {
    // 阻止事件冒泡
    msg.stopPropagation()

    console.log(msg, 'onToShare')
  }

  handleToPage = (pathName, e) => {
    e.stopPropagation()

    Taro.navigateTo({
      url: pathName
    })
  }

  handleGrowClover = () => {
    this.setState(state => ({
      ...state,
      isJoinOpened: true
    }))
  }

  // handleLaunchGoods = () => {
  //   this.setState(state => ({
  //     ...state,
  //     isLanchGoodsOpened: true
  //   }))
  // }

  onCurtainClose = () => {
    this.setState(state => ({
      ...state,
      isJoinOpened: false,
      isLanchGoodsOpened: false
    }))
  }

  // onClick={this.handleSubmits.bind(this, this.$router.params)
  handleSubmits = (params = {}) => {
    this.props.addProfile({...params, goodsPrizeId: this.state.goodsPrizeId}, (data) => {
      if (data.errno || typeof data === 'string' ) {
        Taro.showToast({ title: `${data.errmsg}！`, icon: 'none' })
      } else {
        Taro.showToast({ title: `参与抽奖成功~`, icon: 'none' })
      }
    })
  }

  handleJoin = () => {
    console.log(123321)
    this.setState(state => ({
      ...state,
      isJoinOpened: true
    }))
  }

  onChange = current => {
    const goodsPrizeId = this.props.goods.profile.data.GoodsPrizes[current].id
    this.setState(state => ({
      ...state,
      goodsPrizeId
    }))
  }

  render() {

    const goodsId = this.$router.params.id

    const { visible } = this.state

    const flag = this.props.goods.profile.data && new Date(this.props.goods.profile.data.endAt) < new Date(this.props.goods.profile.updateAt)

    return (
      <View className='profile'>
        <XGood data={this.props.goods.profile.data} onChange={this.onChange} />
        <View className='article' style={{ backgroundColor: '#fff' }}>
          <YTableDivider title='抽奖说明' />
          <View className='content' style={{textAlign: 'justify'}}>
            <Text className='text'>{this.props.goods.profile.data.brief}</Text>
          </View>
          <YTableDivider title='奖品介绍' />
          {
            this.props.goods.profile.data.GoodsFigures.map(item => {
              return <View className='content' key={item.id}>
                <Text className='text'>{item.figcaption}</Text>
                <Image src={image_prefix + item.image} mode='widthFix' className='image' />
              </View>
            })
          }
        </View>

        <View className='paihang'>
          <AtButton size='small' onClick={this.handleToPage.bind(this, `/pages/profile/Integrals`)}>种草排行</AtButton>
          {
            flag && false && <AtButton size='small' onClick={this.handleToPage.bind(this, '/pages/profile/Winnings')}>中奖名单 暂时展位</AtButton>
          }
        </View>

        <View className='profile-menu' onClick={this.handleSubmits.bind(this, this.$router.params)}>
          <Text className='text'>参与抽奖</Text>
        </View>

        <View className='profile-avatar-title'>
          <Text className='text'>参与抽奖，种下幸运草</Text>
        </View>
        <ProfileAvatar data={this.props.goods.users} />
        <View className='profile-avatar-brief' onClick={this.handleToPage.bind(this, '/pages/profile/Users')}>
          <Text className='text'>已有{this.props.goods.users.pagination.count}人参与</Text>
          <Text className='link'>&nbsp;&nbsp;查看全部 ></Text>
        </View>

        <AtList>
          <AtListItem
            title='我的幸运草 x6'
            arrow='right'
            extraText='继续种草'
            onClick={this.handleGrowClover}
          />
        </AtList>

        <View className='profileBtnGroup'>
          <AtButton className='btn btn-first' type='secondary' size='small' onClick={this.handleLaunchGoods}>我也要发起</AtButton>
          <AtButton className='btn btn-last' type='primary' openType='share' size='small' onClick={this.onToShare}>分享给朋友</AtButton>
        </View>
        <AtCurtain
          isOpened={this.state.isJoinOpened}
          onClose={this.onCurtainClose}
        >
          <Image src={join1} mode='widthFix' className='image' style={{ width: '80%', marginLeft: '10%', marginTop: '20%' }} />
          <View className='curtain-abs-grow'>
            <View className='inner'>
              <Text className='text'>我还有幸运草 x6</Text>
              <Image src={cloverIcon} mode='widthFix' className='icon' />
            </View>
            <View className='footer'>
              <Text className='text'>我要再种</Text>
              <Input className='input' />
              <AtButton size='small'>确认种草</AtButton>
              {/*<Text className='more'>获得更多幸运草</Text>*/}
            </View>
          </View>
        </AtCurtain>
        <AtCurtain
          isOpened={this.state.isLanchGoodsOpened}
          onClose={this.onCurtainClose}
        >
          <Image src={join2} mode='widthFix' />
          <View className='curtain-abs-success'>
            <View className='inner'>
              <Text className='text'>您已种下一颗幸运草</Text>
              <Image src={cloverIcon} mode='widthFix' className='icon' />
            </View>
            <View className='footer'>
              <AtButton type='primary' size='small'>分享好友获幸运草</AtButton>
              {/*<View>
                  <Text className='caption'>暂不参与</Text>
              </View>*/}
            </View>
          </View>
        </AtCurtain>


      </View>
    )
  }
}

export default Profile as ComponentClass<PageOwnProps, PageState>